//
//  QYHomeViewController.m
//  QingYue
//
//  Created by 崔明燃 on 2017/3/24.
//  Copyright © 2017年 com.lanou.product_A. All rights reserved.
//

#import "QYHomeViewController.h"
#import "QYHotBookListViewController.h"

#import "QYHomePicHeaderCollectionReusableView.h"
#import "QYHomeCollectionReusableView.h"
#import "QYHomeCollectionViewCell.h"
#import "QYBookDetailViewController.h"

#import "QYHomeBookModel.h"
#import "QYSearchViewController.h"
#import "TopCycleModel.h"
//static CGFloat headerViewHeight = 0;
static NSString *firstHeaderViewIdentifier = @"kFirstRecipeCollectionHeaderViewID";
static NSString *headerViewIdentifier = @"kRecipeCollectionHeaderViewID";

@interface QYHomeViewController () <UICollectionViewDelegate, UICollectionViewDataSource>

@property (strong, nonatomic) UICollectionView *listCollectionView;
@property (strong, nonatomic)  QYHomePicHeaderCollectionReusableView *listFirstHeaderView;
@property (strong, nonatomic)  QYHomeCollectionReusableView *listHeaderView;
@property (nonatomic, strong) UIImageView *tztImageView;
@property (nonatomic, strong) NSMutableArray *dataArr;

@property (nonatomic, strong) NSMutableArray *dataArr1;
@property (nonatomic, strong) NSMutableArray *dataArr2;
@property (nonatomic, strong) NSMutableArray *dataArr3;


/** 轮播图数组*/
@property (nonatomic,strong) NSMutableArray* cycleViewArray;
/** 搜索按钮*/
@property (nonatomic,strong) UIButton* searchButton;

@end

@implementation QYHomeViewController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self loadData];
    
    NSData *data = [kUserDefaults objectForKey:@"tztImage"];
    UIImage *image = [[UIImage alloc] initWithData:data];
    
    _tztImageView.image = image;
    
    [UIView animateWithDuration:.35 animations:^{
        _tztImageView.alpha = 0;
    } completion:^(BOOL finished) {
        _tztImageView.hidden = YES;
    }];    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"北京大学图书馆";
    self.view.backgroundColor = [UIColor blueColor];
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithCustomView:self.searchButton];
    self.navigationItem.rightBarButtonItem = rightButton;

    [self.view addSubview:self.listCollectionView];
    [[UIApplication sharedApplication].delegate.window addSubview:self.tztImageView];
    
}



- (void)loadData {
    
    _dataArr = [NSMutableArray new];
    _cycleViewArray = [NSMutableArray array];
    NSMutableArray<QYHomeBookModel *> *hotList = [NSMutableArray new];
    NSMutableArray<QYHomeBookModel *> *newList = [NSMutableArray new];
    NSMutableArray<QYHomeBookModel *> *guessList = [NSMutableArray new];
    
    [[YCRequestDataService sharedManager] Post:@"GetAdsImg" parameters:nil success:^(id response) {
        if ([response[@"Code"] isEqualToString:@"成功"]) {
            NSLog(@"%@", response);
            [SVProgressHUD dismissWithDelay:.35];
            
            NSArray<NSDictionary *> *hotBooksList = response[@"adsimg"];
            
            [hotBooksList enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                TopCycleModel *model = [[TopCycleModel alloc] initWithDataDic:obj];
                [_cycleViewArray addObject:model];
            }];
            _listFirstHeaderView.picCxCycView.adDataArray = _cycleViewArray;
            [_listCollectionView reloadData];

        }
        
    } failure:^{
        kTimeAfter(1, ^{kShowNet(@"网络或服务器错误");});
        
    }];
    
    [[YCRequestDataService sharedManager] Post:@"GetHotBooks" parameters:nil success:^(id response) {
        if ([response[@"Code"] isEqualToString:@"成功"]) {
            
            [SVProgressHUD dismissWithDelay:.35];
            
            NSArray<NSDictionary *> *hotBooksList = response[@"hotBooksList"];
            
            [hotBooksList enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if (idx == 4) {
                    *stop = YES;
                }
                QYHomeBookModel *model = [[QYHomeBookModel alloc] initWithDataDic:obj];
                [hotList addObject:model];
            }];
            
            
            _dataArr1 = [NSMutableArray arrayWithArray:hotList];
            
            [_listCollectionView reloadData];
        }
        
        
    } failure:^{
        kTimeAfter(1, ^{kShowNet(@"网络或服务器错误");});
        
    }];
    
    [[YCRequestDataService sharedManager] Post:@"GetNewBooks" parameters:nil success:^(id response) {
        if ([response[@"Code"] isEqualToString:@"成功"]) {
            
            [SVProgressHUD dismissWithDelay:.35];
            
            NSArray<NSDictionary *> *newBooksList = response[@"newBooksList"];
            
            [newBooksList enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if (idx == 4) {
                    *stop = YES;
                }
                QYHomeBookModel *model = [[QYHomeBookModel alloc] initWithDataDic:obj];
                [newList addObject:model];
            }];
            
            _dataArr2 = [NSMutableArray arrayWithArray:newList];

            [_listCollectionView reloadData];

        }
        
        
    } failure:^{
        kTimeAfter(1, ^{kShowNet(@"网络或服务器错误");});
        
    }];
    
    NSDictionary *param = @{@"UserName":[kUserDefaults objectForKey:@"username"]};
    
    [[YCRequestDataService sharedManager] Post:@"GetYourLikeBooks" parameters:param success:^(id response) {
        if ([response[@"Code"] isEqualToString:@"成功"]) {
            
            [SVProgressHUD dismissWithDelay:.35];
            
            NSArray<NSDictionary *> *guessBooksList = response[@"aaa"];
            
            [guessBooksList enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if (idx == 4) {
                    *stop = YES;
                }
                QYHomeBookModel *model = [[QYHomeBookModel alloc] initWithDataDic:obj];
                [guessList addObject:model];
            }];
            
            _dataArr3 = [NSMutableArray arrayWithArray:guessList];

            [_listCollectionView reloadData];

        }
        

    } failure:^{
        kTimeAfter(1, ^{kShowNet(@"网络或服务器错误");});
        
    }];


    

}

#pragma mark - button clicked
- (void)moreButtonClicked:(UIButton *)button {
    
    QYBookListTypeStyle style = QYBookListTypeStyleHot;
    
    
    switch (button.tag) {
        case 0:
        {
            style = QYBookListTypeStyleHot;
        }
            break;
            
        case 1:
        {
            style = QYBookListTypeStyleNew;
        }
            break;
            
        case 2:
        {
            style = QYBookListTypeStyleLike;
        }
            break;
    }
    
    QYHotBookListViewController *bookListVC = [[QYHotBookListViewController alloc] initWithTypeStyle:style];
    bookListVC.hidesBottomBarWhenPushed = YES;

    
    [self.navigationController pushViewController:bookListVC animated:YES];
}

#pragma mark - 搜索按钮实现方法
- (void)searchButtonClick
{
    QYSearchViewController *searchVC = [[QYSearchViewController alloc] init];
    searchVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:searchVC animated:YES];
}


#pragma mark - collection delegate and dataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    if (collectionView == _listCollectionView) {
        return 3;
    }
    
    return 0;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (collectionView == _listCollectionView) {
        return 4;
    }
    return 0;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    QYHomeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"kMyCollectionViewCell_ID" forIndexPath:indexPath];
    
    QYHomeBookModel *model;
    if (indexPath.section == 0 && _dataArr1.count > 0) {
        model = _dataArr1[indexPath.row];
    } else if (indexPath.section == 1 && _dataArr2.count > 0) {
        model = _dataArr2[indexPath.row];
    } else if (indexPath.section == 2 && _dataArr3.count > 0) {
        model = _dataArr3[indexPath.row];
    }
    
    cell.model = model;


    
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    if (collectionView == _listCollectionView) {
        if (indexPath.section == 0) {
            _listFirstHeaderView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:firstHeaderViewIdentifier forIndexPath:indexPath];
            _listFirstHeaderView.titleLbl.text = @"热门图书";
            
            _listFirstHeaderView.moreButton.tag = indexPath.section;
            
            [_listFirstHeaderView.moreButton addTarget:self action:@selector(moreButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
            
            if (_cycleViewArray.count > 0) {
                _listFirstHeaderView.picCxCycView.adDataArray = _cycleViewArray;
            }

            return _listFirstHeaderView;
            
        }
        _listHeaderView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerViewIdentifier forIndexPath:indexPath];
        _listHeaderView.backgroundColor = [UIColor whiteColor];
        
        _listHeaderView.moreButton.tag = indexPath.section;
        [_listHeaderView.moreButton addTarget:self action:@selector(moreButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        if (indexPath.section == 1) {
            _listHeaderView.titleLbl.text = @"新书推荐";
        } else if (indexPath.section == 2) {
            _listHeaderView.titleLbl.text = @"猜你喜欢";
        }
        
        return _listHeaderView;
    }
    return nil;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    QYHomeBookModel *model;
    if (indexPath.section == 0 && _dataArr1.count > 0) {
        model = _dataArr1[indexPath.row];
    } else if (indexPath.section == 1 && _dataArr2.count > 0) {
        model = _dataArr2[indexPath.row];
    } else if (indexPath.section == 2 && _dataArr3.count > 0) {
        model = _dataArr3[indexPath.row];
    }
    
    QYBookDetailViewController *bookDetailVC = [[QYBookDetailViewController alloc] init];
    bookDetailVC.hidesBottomBarWhenPushed = YES;
    bookDetailVC.isbn = model.Isbn;
    [self.navigationController pushViewController:bookDetailVC animated:YES];
    
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    if (collectionView == _listCollectionView) {
        return UIEdgeInsetsMake(0, 0, 0, 0);
    }
    
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

/**
 * 定义头视图的尺寸
 */
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    if (collectionView == _listCollectionView) {
        if (section == 0) {
            return CGSizeMake(self.view.bounds.size.width, 200);
        }
        return CGSizeMake(self.view.bounds.size.width, 30);
    }
    return CGSizeMake(self.view.bounds.size.width, 30);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    
    return CGSizeMake([UIScreen mainScreen].bounds.size.width, 10);
}


#pragma mark - layout subviews
- (void)viewWillLayoutSubviews
{
    [_listCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.view);
    }];
    
    [_tztImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.right.equalTo([UIApplication sharedApplication].delegate.window);
    }];
}

#pragma mark - lazy load
- (UIImageView *)tztImageView {
    if (!_tztImageView) {
        _tztImageView = [[UIImageView alloc] init];
    }
    return _tztImageView;
}

- (UICollectionView *)listCollectionView {
    if (!_listCollectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.itemSize = CGSizeMake((self.view.bounds.size.width - 7.5) / 4, (self.view.bounds.size.width - 7.5) / 4*1.25+40);
        flowLayout.minimumInteritemSpacing = .6;
        flowLayout.minimumLineSpacing = .6;
        flowLayout.sectionInset = UIEdgeInsetsMake(0, 1, 0, 1);
        
        _listCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        _listCollectionView.backgroundColor = [UIColor whiteColor];
        
        
        _listCollectionView.dataSource = self;
        _listCollectionView.delegate = self;
        [_listCollectionView registerClass:[QYHomeCollectionViewCell class] forCellWithReuseIdentifier:@"kMyCollectionViewCell_ID"];
        [_listCollectionView registerClass:[QYHomeCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerViewIdentifier];
        [_listCollectionView registerClass:[QYHomePicHeaderCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:firstHeaderViewIdentifier];
    }
    
    return _listCollectionView;
}

- (UIButton *)searchButton
{
    if (!_searchButton) {
        _searchButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _searchButton.frame = CGRectMake(0, 0, 44, 44);
        [_searchButton setImage:[UIImage imageNamed:@"soushuo"] forState:UIControlStateNormal];
        [_searchButton addTarget:self action:@selector(searchButtonClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _searchButton;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
